package com.guldan.core.utils;

/**
 * Created by Silas.
 * Date: 2016/10/1
 * Time: 22:23
 */

import java.io.File;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class StaticResourceUtil {
    private static Logger logger = LoggerFactory.getLogger(StaticResourceUtil.class);
    private static final ConcurrentHashMap<String, String> CACHE_MAP = new ConcurrentHashMap();
    private static String webRootDiskAbsolutePath;
    private static String webContextPath;

    public StaticResourceUtil() {
    }

    public static void initialize(String contextPath, String webDiskPath) {
        webContextPath = contextPath;
        webRootDiskAbsolutePath = webDiskPath;
        logger.info("has been injected with Web context path： {}", webContextPath);
        logger.info("has been injected with Web root disk absolute path： {}", webRootDiskAbsolutePath);
    }

    public static String getWebContextPath() {
        return webContextPath;
    }

    public static String getWebRootDiskAbsolutePath() {
        return webRootDiskAbsolutePath;
    }

    public static String get(String contentPath) {
        try {
            if(CACHE_MAP.containsKey(contentPath)) {
                return (String)CACHE_MAP.get(contentPath);
            } else {
                String ex = getWebRootDiskAbsolutePath() + contentPath;
                File file = new File(ex);
                String version = "?v=" + file.length() + "." + file.lastModified();
                String url = getWebContextPath() + contentPath + version;
                CACHE_MAP.put(contentPath, url);
                return url;
            }
        } catch (Exception var5) {
            logger.error("获取文件版本出错:contentPath=" + contentPath, var5);
            return contentPath;
        }
    }
}
